package com.ts.notice.utils;


import com.alibaba.fastjson2.JSON;
import com.ts.common.core.utils.ApacheHttpUtils;
import com.ts.notice.config.SMSpropertice;
import com.ts.notice.constants.RedisKey;
import com.ts.notice.dto.SMSDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class SMSUtils {

    @Autowired
    private SMSpropertice smSpropertice;

    @Autowired
    private RedisTemplate redisTemplate;

    private String sendPath = "/sms/send?mobile=%s&templateId=%s&value=%s";

    private String statusPath = "/sms/send-status?mobile=%s&taskId=%s";


    public void send(SMSDto smsDto){

        //发送请求并获取响应数据
        Map<String,Object> map = dosend(smsDto);

        //判断短信是否发送
        Integer code = (Integer)map.get("code");
        if (code == 200){
            log.debug("短信发送成功了，{}",map);
        }else {
            //短信发送失败，存储到redis中，启用定时任务去补偿
            String taskId = smsDto.getTaskId();
            redisTemplate.opsForSet().add(RedisKey.SEND_SMS_ERROR_KEY,smsDto);
        }

    }

    public Boolean query(String phone,String taskId){
        String method = "GET";

        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + smSpropertice.getAppcode());

        String json = ApacheHttpUtils.getUrl(smSpropertice.getHost() + smSpropertice.getAppcode(), headers);
        log.debug("查询短信的状态：{}",json);

        Map map = JSON.parseObject(json, Map.class);

        Integer code = (Integer) map.get("code");

        return code == 200;
    }

    private Map<String, Object> dosend(SMSDto smsDto) {
        sendPath = String.format(sendPath, smsDto.getPhone(), "M105EABDEC", smsDto.getCode());
        String method = "POST";

        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + smSpropertice.getAppcode());

        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", "15016532611");
        querys.put("templateId", "M105EABDEC");
        querys.put("value", "6666");

        String response = ApacheHttpUtils.postJson(smSpropertice.getHost() + sendPath, headers,null);

        log.debug("短信发送结果：{}", response);
        return JSON.parseObject(response,Map.class);
    }
}
